<template>
<div>
  <!-- 暂时隐藏主题设置，目前没有这个内容 -->
  <div class="tab-box">
    <div class="title">主题设置</div>
    <div class="content">
      <div class="tag-list">
        <el-tag
          v-for="item in groupList"
          :class="[groupName === item.value ? 'current' : '', 'tag']"
          type="info"
          :key="item.value"
          @click="() => handleChangeGroup(item.value)"
        >
          {{ item.label }}
        </el-tag>
      </div>
      <div class="banner-list-wrapper">
        <div
          class="single-banner-wrapper"
          v-for="(banner, bannerIndex) in currentBannerList"
          :key="bannerIndex"
        >
          <img class="banner-img" src="@/assets/images/17e06b7604a007e1d3e1453b9ddadc3c.webp" loading="lazy" 
          @click="changePreset(banner)" v-if="banner.src&&banner.src.includes('17e06b7604a007e1d3e1453b9ddadc3c.webp')" />
          <img class="banner-img" :src="banner.src" loading="lazy" @click="changePreset(banner)" v-else />
        </div>
      </div>
    </div>
  </div>
  <div class="setter-wrapper">
    <div class="setter-title">表单页样式设置</div>
    <div class="setter-content">
      <el-collapse v-model="collapse">

        <el-collapse-item
          v-for="(collapse, index) in skinConfig"
          :key="index"
          :title="collapse.name"
          :name="collapse.key"
        >
          <SetterField
            :form-config-list="collapse.formConfigList"
            :module-config="_get(schema, collapse.key, {})"
            @form-change="
              (key) => {
                handleFormChange(key, collapse.key)
              }
            "
          />
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
  <div class="tab-box">
    <div class="title">结果页内容设置</div>
    <div class="status-list-wrapper">
      <div class="status-list-tab">
        <div
          v-for="(status, index) in statusList"
          :key="index"
          class="status-item" :class="{ active: status.type === resultStatus }"
          @click="handleChangePreview({ type: status.type })"
        >
          <span>{{ status.title }}</span>
        </div>
      </div>
      
      <el-form class="result-config-form" label-position="top" @submit.prevent>
        <template v-for="(item, index) in resultFormFields" :key="index">
          <FormItem
            v-if="item.type && !item.hidden && Boolean(registerTypes[item.type])"
            :form-config="item"
            :style="item.style"
          >
            <Component
              v-if="Boolean(registerTypes[item.type])"
              :is="components[item.type]"
              :module-config="moduleConfig"
              :form-config="item"
              @form-change="handleResultFormChange"
            />
          </FormItem>
        </template>
      </el-form>
    </div>
  </div>
</div>
</template>
<script setup lang="ts" name="SkinSetterPanel">
import { computed, ref, shallowRef } from 'vue'
import { useStore } from 'vuex'
import { get as _get } from 'lodash-es'

import skinConfig from '@/management/config/setterConfig/skinConfig'
import SetterField from '@/management/pages/edit/components/SetterField.vue'
import skinPresets from '@/management/config/skinPresets.js'
import { EDIT_STATUS_MAP } from '../enum'

import FormItem from '@/materials/setters/widgets/FormItem.vue'
import setterLoader from '@/materials/setters/setterLoader'
import statusConfig from '../config/statusConfig'

const store = useStore()
const collapse = ref<string>('')
const schema = computed(() => _get(store.state, 'editform.schema'))

const handleFormChange = (data: any, collapse: string) => {
  const { key, value } = data
  const currentEditKey = `${collapse}`
  const resultKey = `${currentEditKey}.${key}`

  store.dispatch('editform/changeSchema', { key: resultKey, value })
}

// 模板列表
const groupName = ref<string>('temp')
const bannerList = computed(() => store?.state?.bannerList || [])
// console.log('bannerList.value', bannerList.value)
const groupList = computed(() =>
  Object.keys(bannerList.value).map((key) => ({
    label: bannerList.value[key].name,
    value: key
  }))
)
const currentBannerList = computed(() => {
  const arr = Object.keys(bannerList.value)
    .map((key) => {
      return bannerList.value[key]
    })
    .map((data) => {
      return data.list.map((item: any) => {
        item.group = data.key
        return item
      })
    })

  const allbanner = arr.reduce((acc, curr) => {
    return acc.concat(curr)
  }, [])

  return allbanner.filter((item: any) => {
    if (groupName.value === 'temp') {
      return true
    } else {
      return item.group === groupName.value
    }
  })
})

const handleChangeGroup = (value: string) => {
  groupName.value = value
}

const changePreset = (banner: any) => {
  const name = banner.group + '-' + banner.title
  let presets = {
    'bannerConf.bannerConfig.bgImage': banner.src,
    'skinConf.themeConf.color': '#0081fa',
    'skinConf.backgroundConf.color': '#fff'
  }

  if ((skinPresets as any)[name]) {
    presets = Object.assign(presets, (skinPresets as any)[name])
  }

  store.dispatch('editform/changeThemePreset', presets)
}

// 结果页面
const statusList = [
  {
    type: EDIT_STATUS_MAP.SUCCESS,
    title: '提交成功',
    previewImg: '/myactivity/imgs/icons/success.webp'
  },
  {
    type: EDIT_STATUS_MAP.OVERTIME,
    title: '活动过期',
    previewImg: '/myactivity/imgs/icons/overtime.webp'
  }
]

const resultStatus = ref(EDIT_STATUS_MAP.SUCCESS)
const handleChangePreview = (data: any) => {
  const currentStatus = store.state?.editform?.currentEditStatus
  resultStatus.value = data.type
  if (currentStatus && currentStatus !== data.type) {
    store.commit('editform/changeStatusPreview', data)
  }
}

const components = shallowRef<any>({})
const registerTypes = ref<any>({})
const moduleConfig = computed(() => _get(store.state, 'editform.schema.submitConf'))
const resultFormFields = computed(() => {
  const currentStatus = store.state.editform.currentEditStatus
  const formList = (statusConfig as any)[currentStatus] || []
  const list = formList.map((item: any) => {
    const value = _get(moduleConfig.value, item.key, item.value)

    return { ...item, value }
  })

  registerComponents(list)

  return list
})

const handleResultFormChange = ({ key, value }: any) => {
  store.dispatch('editform/changeSchema', {
    key: `submitConf.${key}`,
    value
  })
}

const registerComponents = async (formFieldData: any) => {
  const setters = formFieldData.map((item: any) => item.type)
  const settersSet = new Set(setters)
  const settersArr = Array.from(settersSet)
  // console.log('settersArr', settersArr)
  const allSetters = settersArr.map((item) => {
    return {
      type: item,
      path: item
    }
  })

  try {
    const comps = await setterLoader.loadComponents(allSetters)

    for (const comp of comps) {
      if (!comp) {
        continue
      }

      const { type, component, err } = comp

      if (!err) {
        const componentName = component.name

        components.value[type] = component
        registerTypes.value[type] = componentName
      }
    }
  } catch (err) {
    console.error(err)
  }
}
</script>
<style lang="scss" scoped>
.setter-wrapper {
  width: 360px;
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;
  background-color: #fff;
}

.setter-title {
  height: 40px;
  line-height: 40px;
  font-size: 14px;
  color: $primary-color;
  padding-left: 20px;
  // background: #f9fafc;
  border-bottom: 1px solid #edeffc;
}
.setter-content {
  padding: 10px 20px;
  .el-collapse {
    border: none;
    :deep(.el-collapse-item__header) {
      font-size: 14px;
      color: #606266;
      font-weight: bold;
      border: none;
    }
    :deep(.el-collapse-item__wrap) {
      border: none;
      .el-collapse-item__content {
        padding-bottom: 0px !important;
      }
    }
  }
  .config-form {
    padding: 0 !important;
  }
}

.tab-box {
  width: 360px;
  height: 100%;
  box-shadow: none;
  border: none;
  overflow-y: auto;
  background-color: #fff;
  .title {
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    color: $primary-color;
    padding-left: 20px;
    // background: #f9fafc;
    border-bottom: 1px solid #edeffc;
  }
  .content {
    padding: 12px;
  }
  .tag-list {
    display: flex;
    flex-wrap: wrap;
    .tag {
      margin: 5px 8px;
      cursor: pointer;
      &.current {
        color: $primary-color;
        background-color: $primary-bg-color;
      }
    }
  }
  .banner-list-wrapper {
    padding: 15px 3px 10px 3px;
    overflow-x: hidden;

    .banner-img {
      position: relative;
      margin-bottom: 10px;
      width: 100%;
      // min-height: 111px;
      cursor: pointer;
      transition: all 0.2s;
      border-radius: 4px;
      &:hover {
        -webkit-filter: brightness(90%);
        filter: brightness(90%);
      }
    }

    :deep(.el-collapse-item__header) {
      font-size: 16px;
      color: $font-color-title;
      border-bottom: none;
    }

    :deep(.el-collapse-item__arrow.is-active) {
      right: 0;
    }
    :deep(.el-collapse-item__arrow) {
      right: 0;
    }
  }
}
.result-config-form {
  padding: 20px;
}

.status-list-wrapper {
  .status-list-tab {
    margin-top: 10px;
    display: flex;
    justify-content: center;
  }

  .status-item {
    line-height: 1;
    white-space: nowrap;
    vertical-align: middle;
    font-size: $font-size-small;
    background: var(--el-button-bg-color, var(--el-fill-color-blank));
    border: var(--el-border);
    font-weight: var(--el-button-font-weight, var(--el-font-weight-primary));
    // border-left: 0;
    color: var(--el-button-text-color, var(--el-text-color-regular));
    -webkit-appearance: none;
    text-align: center;
    box-sizing: border-box;
    outline: none;
    margin: 0;
    position: relative;
    cursor: pointer;
    transition: var(--el-transition-all);
    user-select: none;
    padding: 6px 15px;
  }
  .status-item + .status-item {
    border-left: 0;
  }
  .status-item:first-child {
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
  }
  .status-item:last-child {
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
  }
  .status-item:hover,
  .status-item.active {
    border: 1px solid var(--el-color-primary);
    color: var(--el-color-primary);
  }
}
</style>
